from flask import Flask, request, jsonify

from model import User, db_session

import hashlib
import time
import redis

from functools import wraps


# 返回token验证结果 
def login_check(f):
	'''
	@'code':3 'token not exist in redis'
	@'code':4 'phone_number not exist in redis'
	'''
	@wraps(f)
	def decorater(*args, **argvs):
		token = request.headers.get('token')
		if not token:
			return jsonify( {'code':3, 'message': 'token not exist in redis'} )
		phone_number = redis_store.get(token)
		if not phone_number or phone_number != redis_store.hget('user:%s' % phone_number, 'token'):
			return jsonify( {'code':4, 'message': 'phone_number not exist in redis'} )
		return f(*args, **argvs)

	return decorater


# 返回一个redis链接
def rhandle():
	REDIS_HOST = 'localhost'
	REDIS_PORT = 6379
	REDIS_DB = 4
	pool = redis.ConnectionPool(db=REDIS_DB, host=REDIS_HOST, port=REDIS_PORT)
	r = redis.Redis(connection_pool=pool)

	return r


redis_store = rhandle()
app = Flask(__name__)



@app.route('/')
def home():
	return 'Hay'


@app.route('/register', methods=['POST'])
def register():
	pass
	'''
	@
	'''
	phone_number = request.get_json().get('phone_number')
	password = request.get_json().get('password')
	user = User(phone_number=phone_number, password=password)
	db_session.add(user)
	try:
		db_session.commit()
		return jsonify({'code':0, 'message':'Regist sucessed!!!'})
	except Exception as e:
		db_session.rollback()
		raise


@app.route('/login', methods=['POST'])
def login():
	'''
	@'code':1 'User not exist in database!'
	@'code':2 'Password error in database!'
	'''
	phone_number = request.get_json().get('phone_number')
	password = request.get_json().get('password')
	user = User.query.filter_by(phone_number=phone_number).first()

	if not user:
		return jsonify( {'code':1, 'message': 'User not exist in database!'} )
	if user.password != password:
		return jsonify( {'code':2, 'message': 'Password error in database!'} )

	# 生成token
	m = hashlib.md5()
	m.update(phone_number.encode('utf-8'))
	m.update(password.encode('utf-8'))
	m.update(str(int(time.time())).encode('utf-8'))
	token = m.hexdigest()

	# pipeline 解决通道中断 数据丢失
	pipeline = redis_store.pipeline()
	pipeline.hmset('user:%s' % user.phone_number,{'token':token,'nickname':user.nickname,'app_online':1})
	pipeline.set('token:%s' % token, user.phone_number)
	pipeline.expire('token:%s' % token, 3600*24*30)		#token有效期1个月
	pipeline.execute()

	return jsonify({'code':0, 'message':'Login sucessed!!!','nickname':user.nickname, 'token':token})


@app.route('/logout')
@login_check
def user():
	'''
	@用户信息展示 验证是否登录
	'''
	pass


@app.teardown_request
def handle_teardown_request(e):
	'''
	@
	'''
	db_session.remove()



if __name__ == '__main__':
	app.run(debug=True, host='0.0.0.0', port=80)
